#!/usr/bin/python3
# -*- coding: utf-8 -*-

# www.cnblogs.com/nancyzhu/p/8551506.html

import logging
from logging import handlers


class Logger(object):
    level_relations = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'critical': logging.CRITICAL
    }  # 日志级别关系映射

    # '%(asctime)s - %(levelname)s - %(name)s - %(message)s'
    def __init__(
            self, filename, level='info', when='D', backCount=3,
            fmt='%(asctime)s - %(pathname)s - %(funcName)s:%(lineno)d - %(levelname)s: %(message)s'):  # noqa

        self.logger = logging.getLogger(filename)
        format_str = logging.Formatter(fmt)  # 设置日志格式
        self.logger.setLevel(self.level_relations.get(level))  # 设置日志级别
        sh = logging.StreamHandler()  # 往屏幕上输出
        sh.setFormatter(format_str)  # 设置屏幕上显示的格式
        # 往文件里写入#指定间隔时间自动生成文件的处理器
        th = handlers.TimedRotatingFileHandler(
                filename=filename,
                when=when,  # 间隔的时间单位(S,M,H,D,W,midnight: 秒,分,小时,天,周,凌晨)
                backupCount=backCount,  # 备份文件的个数，如果超过这个个数，就会自动删除
                encoding='utf-8')
        th.setFormatter(format_str)  # 设置文件里写入的格式
        self.logger.addHandler(sh)  # 把对象加到logger里
        self.logger.addHandler(th)


if __name__ == '__main__':
    log = Logger('all.log', level='debug')
    log.logger.debug('debug')
    log.logger.info('info')
    log.logger.warning('警告')
    log.logger.error('报错')
    log.logger.critical('严重')
    Logger('error.log', level='error').logger.error('error')
